package cn.hg.base.jfinal.validator;

import com.jfinal.validate.ValidateException;
import com.jfinal.validate.Validator;

import cn.hg.base.jfinal.controller.BaseController;

/**
 * @author Golly
 */
public abstract class BaseValidator extends Validator {

	protected static final String filePattern = "[\\\\\\\\/:*?\\\"<>|]";
	protected static final String mobilePhonePattern =
		"^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$";
	protected static final String telePhonePattern = "\\d{3}-\\d{8}|\\d{4}-\\d{7}";

	/*
	 * (non-Javadoc)
	 * @see com.jfinal.validate.Validator#addError(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	protected void addError (String errorKey, String errorMessage) {
		this.invalid = true;

		// 重载原方法，如果调用方式为Ajax，则返回Json格式的错误信息
		if (this.controller instanceof BaseController) {
			BaseController bc = (BaseController) this.controller;

			if (bc.isAjaxRequest()) {
				bc.renderAjaxFailed("1", errorMessage);
			} else {
				this.controller.setAttr(errorKey, errorMessage);
			}

			throw new ValidateException();
		} else {
			this.controller.setAttr(errorKey, errorMessage);

			if (this.shortCircuit) {
				throw new ValidateException();
			}

		}

	}

	/**
	 * Validate tele phone.
	 */
	protected void validateFileName (String field, String errorKey, String errorMessage) {
		this.validateRegex(field, BaseValidator.filePattern, false, errorKey, errorMessage);
	}

	/**
	 * Validate mobile phone.
	 */
	protected void validateMobilePhone (String field, String errorKey, String errorMessage) {
		this.validateRegex(field, BaseValidator.mobilePhonePattern, false, errorKey, errorMessage);
	}

	/**
	 * Validate tele phone.
	 */
	protected void validateTelePhone (String field, String errorKey, String errorMessage) {
		this.validateRegex(field, BaseValidator.telePhonePattern, false, errorKey, errorMessage);
	}

}
